package com.listen.service.DB;

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.listen.common.DateFormatUtil;
import com.listen.common.GetPictureVerificationCode;
import com.listen.common.HttpClientProxy;
import com.listen.common.HttpClientUtil;
import com.listen.common.ImageToHex;
import com.listen.vo.XunwangVO;
import com.listen.model.User;
import com.listen.vo.HeadParmsVO;

import net.sf.json.JSONObject;

/**
 * 讯网网课
 * @author rain
 * http://zkexam.qmth.com.cn/exam/login.thtml
 */
public class XunwangServiceImpl {
	private static final Logger log = LoggerFactory.getLogger(XunwangServiceImpl.class);
	private HttpClientProxy instance = new HttpClientProxy();
	private ThreadLocal<String> referer = new ThreadLocal<String>();
	private String index_url = "http://zkexam.qmth.com.cn/index.html";
	private String picUrl = "http://zkexam.qmth.com.cn/exam/inc/checkcode.jsp?t="+Math.random();
	
	public static void main(String[] args) throws Exception {
		XunwangServiceImpl xunwang = new XunwangServiceImpl();
		User user = new User();
		XunwangVO xunwangVO = new XunwangVO();
		user.setCode("019818220795");
		user.setPassword("101457");
		user.setCompanyName("89e3fc5a-8ba4-442e-845a-ba33ab77b8cb");
		xunwang.indexPage(user,xunwangVO);
	}
	
	public void indexPage(User user,XunwangVO xunwangVO) throws Exception{
		CloseableHttpResponse response = null;
		CloseableHttpClient httpClient = null;
		try {
			
			response = instance.sendHttpGet(httpClient,index_url, null);
			int state = response.getStatusLine().getStatusCode();
			if(state == 200){
				HttpEntity entity = response.getEntity();
				String html = EntityUtils.toString(entity);
				Document document = Jsoup.parse(html);
				Elements elements  = document.select("div.main_content ul li");
				for(Element element : elements) {
					Elements els = element.getElementsByClass("hszz");
					for(Element el : els) {
						String text = el.text();
						if("湖北国土资源职业学院".equals(text)) {
							Elements as = element.getElementsByAttribute("href");
							xunwangVO.setBaseUrl(as.attr("href"));
							//System.out.println(baseUrl);
						}
					}
				}
				openPage(user,xunwangVO);
			}
		} catch (Exception e) {
			user.setFinished(true);
			log.error("打开登录页面异常--->",e);
		}finally {
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	
	//1-打开登录页面
	public void openPage(User user,XunwangVO xunwangVO) throws Exception{
		CloseableHttpResponse response = null;
		CloseableHttpClient httpClient = null;
		String url = xunwangVO.getBaseUrl() + "login.thtml";
		try {
			user.setReferer(url);
			response = instance.sendHttpGet(httpClient,url, null);
			int state = response.getStatusLine().getStatusCode();
			if(state == 200){
				Header[] hearders = response.getHeaders("Set-Cookie");
				String sessionIds = hearders[0].getValue();
        		String sessionId = sessionIds.substring(0, sessionIds.indexOf(";"));
        		user.setCookie(sessionId);
        		xunwangVO.setCodePictureName(downloadImage(user,xunwangVO));
				String picCode = GetPictureVerificationCode.getVerificationCode(xunwangVO.getCodePictureName(),false);
				xunwangVO.setPicCode(picCode);
				login(user,xunwangVO);
			}
		} catch (Exception e) {
			user.setFinished(true);
			log.error("打开登录页面异常--->",e);
		}finally {
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	//2-登录
	public void login(User user,XunwangVO xunwangVO) throws Exception{
		CloseableHttpResponse response = null;
		CloseableHttpClient httpClient = null;
		String url = xunwangVO.getBaseUrl() + "common/login.do";
		Map<String, String> maps = new HashMap<String, String>();
		try {
			maps.put("username", user.getCode()); //用户账号
	        maps.put("userpass",user.getPassword());//用户密码 
	        maps.put("usertype","0");//用户类型
	        maps.put("usercode",xunwangVO.getPicCode());//验证码
	        maps.put("t", Math.random()+"");//学员登录 
			String cookie = user.getCookie();
	        
			HeadParmsVO head = new HeadParmsVO();
	        head.setAccept("application/json, text/javascript, */*; q=0.01");
	        head.setxRequestedWith("XMLHttpRequest");
			head.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
			head.setReferer(referer.toString());
			head.setCookie(cookie);
			head.setConnection("keep-alive");
			
			response = instance.sendHttpPost(httpClient, head, url, maps, null);
			int state = response.getStatusLine().getStatusCode();
			if(state == 200){
				HttpEntity entity = response.getEntity();  
				String html = EntityUtils.toString(entity,"UTF-8");
				JSONObject json = JSONObject.fromObject(html);
				String code = json.getString("code");
				if("1".equals(code)) {
					//将验证码二进制数据保存到本地文件中，作为数据字典
					//1.获取二进制数据
					List<String> binaryList = GetPictureVerificationCode.getBinaryList(xunwangVO.getCodePictureName());
					//2.将二进制数据写入字典
					for(String s : binaryList) {
						GetPictureVerificationCode.saveDictionary(s);
					}
					//3.删除验证码图片
					GetPictureVerificationCode.deleteFile(xunwangVO.getCodePictureName());
					
					//4.进入课件学习页面
					classStudy(user,xunwangVO);
				}else {
					//登录失败
					Thread.sleep(3000);
					log.info("登录失败，返回代码--->重新登录");
					openPage(user,xunwangVO);
				}
			}
		} catch (Exception e) {
			user.setFinished(true);
			log.error("打开登录页面异常--->",e);
		}finally {
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	
	//3-点击课件学习
	public void classStudy(User user,XunwangVO xunwangVO) throws Exception{
		CloseableHttpResponse response = null;
		CloseableHttpClient httpClient = null;
		String url = xunwangVO.getBaseUrl() + "user/kjxx/baoming.thtml";
		try {
			HeadParmsVO heads = new HeadParmsVO();
			heads.setCookie(user.getCookie());
			response = instance.sendHttpGet(httpClient,heads,url, null);
			int state = response.getStatusLine().getStatusCode();
			if(state == 200){
				HttpEntity entity = response.getEntity();
				String html = EntityUtils.toString(entity);
				Document document = Jsoup.parse(html);
				Elements elements  = document.select("div.left_nav ul li");
				xunwangVO.setUrlMap(new HashMap<String,String>());
				for(Element element : elements) {
					Elements els = element.getElementsByTag("span");
					Elements as = element.getElementsByTag("a");
					String href = as.attr("href");
					for(Element el : els) {
						String text = el.text();
						xunwangVO.getUrlMap().put(text, href);
					}
				}
				myCourseLearns(user,xunwangVO);
			}
		}catch (Exception e) {
			user.setFinished(true);
			log.error("打开classStudy页面异常--->",e);
		}finally {
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	
	//4.点击我的课件
	public void myCourseLearns(User user,XunwangVO xunwangVO) throws Exception{
		CloseableHttpResponse response = null;
		CloseableHttpClient httpClient = null;
		String url = null;
		for(Map.Entry<String, String> map : xunwangVO.getUrlMap().entrySet()) {
			if("我的课件".equals(map.getKey())) {
				url = map.getValue();
			}
		}
		if(url == null) return;
		url = xunwangVO.getBaseUrl() + url;
		this.referer.set(url);
		try {
			HeadParmsVO heads = new HeadParmsVO();
			heads.setCookie(user.getCookie());
			response = instance.sendHttpGet(httpClient,heads,url, null);
			int state = response.getStatusLine().getStatusCode();
			if(state == 200){
				xunwangVO.setParamList(new ArrayList<String>());
				HttpEntity entity = response.getEntity();
				String html = EntityUtils.toString(entity);
				Document document = Jsoup.parse(html);
				Elements elements  = document.select("div.zs_table table tr");
				for(Element element : elements) {
					Elements els = element.getElementsByTag("a");
					for(Element el : els) {
						Elements es = el.getElementsByAttribute("onclick");
						String fun = es.attr("onclick");
						String sm = fun.substring(fun.indexOf("(")+1,fun.indexOf(")")).replace("'", "");
						xunwangVO.getParamList().add(sm);
						//System.out.println(sm);
					}
				}
				user.setType(1);
				getUnreadCount(user,xunwangVO);
			}else {
				log.error("打开myCourseLearns页面失败-->",state);
			}
		}catch (Exception e) {
			user.setFinished(true);
			//logout(user,xunwangVO);
			log.error("打开我的课件页面异常--->",e);
		}finally {
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	
	//获取未看课程
	public void getUnreadCount(User user,XunwangVO xunwangVO) throws Exception{
		CloseableHttpResponse response = null;
		CloseableHttpClient httpClient = null;
		String url = xunwangVO.getBaseUrl() + "user/news/getUnreadCount.do";
		try {
			HeadParmsVO heads = new HeadParmsVO();
			heads.setCookie(user.getCookie());
			response = instance.sendHttpGet(httpClient,heads,url, null);
			int state = response.getStatusLine().getStatusCode();
			if(state == 200){
				HttpEntity entity = response.getEntity();
				String html = EntityUtils.toString(entity,"UTF-8");
				JSONObject json = JSONObject.fromObject(html);
				String code = json.getString("code");
				if("ok".equals(code)) {
					if(user.getType() == 1) {
						courseLearn(user,xunwangVO);
					}if(user.getType() == 2) {
						contentList(user,xunwangVO);
					}
				}
			}
		}catch (Exception e) {
			user.setFinished(true);
			log.error("打开getUnreadCount页面异常--->",e);
		}finally {
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	
	
	//课件学习
	public void courseLearn(final User user,final XunwangVO xunwangVO) throws Exception{
		CloseableHttpResponse response = null;
		CloseableHttpClient httpClient = null;
		xunwangVO.setMinuList(new ArrayList<Map<String,String>>());
		try {
			//每循环一次代表一门课程|每门课程都有很多个课时
			for(int i = 0;i < xunwangVO.getParamList().size() ; i++) {
				String param = xunwangVO.getParamList().get(i);
				System.out.println("课程"+(i+1)+"的参数："+param);
				xunwangVO.setTid(param.split(",")[0].trim());
				xunwangVO.setCid(param.split(",")[1].trim());
				xunwangVO.setLcid(param.split(",")[2].trim());
				String url = xunwangVO.getBaseUrl() + "user/kjxx/courseLearn.thtml?id="+xunwangVO.getLcid();
				HeadParmsVO heads = new HeadParmsVO();
				heads.setCookie(user.getCookie());
				response = instance.sendHttpGet(httpClient,heads,url, null);
				int state = response.getStatusLine().getStatusCode();
				if(state == 200){
					HttpEntity entity = response.getEntity();
					String html = EntityUtils.toString(entity);
					Document document = Jsoup.parse(html);
					Element elt = document.getElementById("c_cid");
					xunwangVO.setC_cid(elt.attr("value"));
					
					Elements elements  = document.select("div.kcml div ul li ul li");
					for(Element element : elements) {
						Map<String,String> minuMap = new HashMap<String,String>();
						String lesson_id = element.attr("lesson_id");
						String chapter_id = element.attr("chapter_id");
						Elements els = element.select("span.progress_info span");
						String nowMins = els.get(0).text().trim();
						String allMins = els.get(1).text().trim();
						minuMap.put("nowMins", nowMins);
						minuMap.put("allMins", allMins);
						minuMap.put("lesson_id", lesson_id);
						minuMap.put("chapter_id", chapter_id);
						xunwangVO.getMinuList().add(minuMap);
					}
					user.setType(2);
					getUnreadCount(user,xunwangVO);
				}else {
					log.error("打开courseLearn页面失败-->",state);
				}
			}
		}catch (Exception e) {
			user.setFinished(true);
			logout(user,xunwangVO);
			log.error("打开我的课件页面异常--->",e);
		}finally {
			HttpClientUtil.getInstance().closeResource(response);
		}
		logout(user,xunwangVO);
	}
	
	//内容播放页面
	public void contentList(User user,XunwangVO xunwangVO) throws Exception{
		CloseableHttpResponse response = null;
		CloseableHttpClient httpClient = null;
		String url = xunwangVO.getBaseUrl() + "user/kjxx/contentList.thtml?epage=1&epagesize=20&c_cid="+xunwangVO.getC_cid();
		try {
			HeadParmsVO heads = new HeadParmsVO();
			heads.setCookie(user.getCookie());
			response = instance.sendHttpGet(httpClient,heads,url, null);
			int state = response.getStatusLine().getStatusCode();
			if(state == 200){
				HttpEntity entity = response.getEntity();
				String html = EntityUtils.toString(entity,"UTF-8");
				JSONObject json = JSONObject.fromObject(html);
				String code = json.getString("code");
				if("ok".equals(code)) {
					doloop(user,xunwangVO);
				}
			}
		} catch (Exception e) {
			user.setFinished(true);
			log.error("打开contentList页面异常",e);
		}finally {
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	
	public void doloop(User user,XunwangVO xunwangVO) throws Exception {
		for(int i = 0;i< xunwangVO.getMinuList().size(); i++) {
			Map<String, String>  minuMap = xunwangVO.getMinuList().get(i);
			xunwangVO.setLessonid(minuMap.get("lesson_id"));
			xunwangVO.setChapterid(minuMap.get("chapter_id"));
			int allMins = Integer.parseInt(minuMap.get("allMins"));
			int nowMins = Integer.parseInt(minuMap.get("nowMins"));
			if(nowMins == allMins)
				continue;
			System.out.println(nowMins+"="+allMins);
			xunwangVO.setAllMins(allMins);
			xunwangVO.setNowMins(nowMins);
			//100秒一次上传图片
			//60秒一次标记进度
			try {
				int c = 0,u = 0;
				xunwangVO.setFlag(true);
				while(xunwangVO.isFlag()) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					if(c % 60 == 0) {
						coursemarker(user,xunwangVO);
					}
					if(u % 100 == 0) {
						uploadViewVideoPhoto(user,xunwangVO);
					}
					c++;u++;
				}
			} catch (Exception e) {
				user.setFinished(true);
				xunwangVO.setFlag(false);
			}
			//5分钟一次答题
		}
	}
	
	/**
	 *	标记课程进度 返回{"msg":"操作成功","cphId":"3bd7d91b-a278-4f01-b2d1-493dc148875e","code":"ok","curPlayed":3,"finished":false,"studyCode":1}
	 */
	public void coursemarker(User user,XunwangVO xunwangVO) throws Exception{
		CloseableHttpResponse response = null;
		CloseableHttpClient httpClient = null;
		String url = xunwangVO.getBaseUrl() + "user/kjxx/coursemarker.do";
		int nowMin = xunwangVO.getNowMins();
		int allMin = xunwangVO.getAllMins();
		Map<String,String> paramMap = new HashMap<String,String>();
		try {
			paramMap.put("id", xunwangVO.getLcid());
			paramMap.put("chapterid", xunwangVO.getChapterid());
			paramMap.put("lessonid", xunwangVO.getLessonid());
			paramMap.put("minutes",allMin+"");
			if(nowMin > 0)
				paramMap.put("playTimelength",nowMin+"");
			paramMap.put("learnType", "课件学习");
			paramMap.put("t", Math.random()+"");
			
			if(nowMin < allMin) nowMin++;
			HeadParmsVO heads = new HeadParmsVO();
			heads.setCookie(user.getCookie());
			heads.setAccept("application/json, text/javascript, */*; q=0.01");
			heads.setAcceptEncoding("gzip, deflate");
			heads.setConnection("keep-alive");
			heads.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
			heads.setxRequestedWith("XMLHttpRequest");
			response = instance.sendHttpPost(httpClient,heads,url,paramMap,null);
			int state = response.getStatusLine().getStatusCode();
			if(state == 200){
				HttpEntity entity = response.getEntity();
				String html = EntityUtils.toString(entity,"UTF-8");
				JSONObject json = JSONObject.fromObject(html);
				String code = json.getString("code");
				if("ok".equals(code)) {
					System.out.println("进度标记成功："+html  +"  nowMin="+nowMin);
					xunwangVO.setCphId(json.getString("cphId"));
					int curPlayed = json.getInt("curPlayed");
					nowMin = (nowMin <= curPlayed) ? curPlayed : nowMin;
					xunwangVO.setNowMins(nowMin);
					if(json.getBoolean("finished")) {
						xunwangVO.setFlag(false);
						studyFinished(user,xunwangVO);
					}
				}else {
					System.out.println("进度标记失败："+html);
				}
			}else {
				System.out.println("进度标记失败："+state);
			}
		} catch (Exception e) {
			user.setFinished(true);
			log.error("Finished="+user.isFinished() +" coursemarker执行异常",e);
		}finally {
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	
	public void uploadViewVideoPhoto(User user,XunwangVO xunwangVO) throws Exception{
		CloseableHttpResponse response = null;
		CloseableHttpClient httpClient = null;
		//post请求
		String picName = getbaseImgaeUrl() + user.getCode() + ".jpg";
		String url = xunwangVO.getBaseUrl() + "uploadViewVideoPhoto.do?courseId="+xunwangVO.getC_cid()+"&userId="+user.getCompanyName();
		try {
			HeadParmsVO heads = new HeadParmsVO();
			heads.setCookie(user.getCookie());
			heads.setContentType("application/x-www-form-urlencoded");
			heads.setConnection("keep-alive");
			heads.setAccept("*/*");
			heads.setAcceptEncoding("gzip, deflate");
			heads.setAcceptLanguage("zh-CN,zh;q=0.9");
			heads.setxRequestedWith("ShockwaveFlash/29.0.0.171");
			Map<String,String> paramMap = new HashMap<String,String>();
			String hexStr = ImageToHex.getHexStrByRGB(picName);
			paramMap.put("width", "320");
			paramMap.put("height", "240");
			paramMap.put("rgb_array",hexStr);
			
			response = instance.sendHttpPost(httpClient, heads, url, paramMap, null);
			
			int state = response.getStatusLine().getStatusCode();
			if(state == 200) {
				HttpEntity entity = response.getEntity();
				String html = EntityUtils.toString(entity,"UTF-8");
				JSONObject json = JSONObject.fromObject(html);
				String code = json.getString("code");
				if("y".equals(code)) {
					System.out.println("人脸识别成功："+html);
					xunwangVO.setFullpath(json.getString("fullpath"));
					logViewVideoPhoto(user,xunwangVO);
				}else {
					log.error("上传人脸识别截图失败--->code="+html);
				}
			}
		} catch (Exception e) {
			user.setFinished(true);
			log.error("上传人脸识别图片失败-->",e);
		}finally {
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	
	private void logViewVideoPhoto(User user,XunwangVO xunwangVO) throws Exception{
		CloseableHttpResponse response = null;
		CloseableHttpClient httpClient = null;
		String url = xunwangVO.getBaseUrl() + "user/kjxx/logViewVideoPhoto.do";
		try {
			HeadParmsVO heads = new HeadParmsVO();
			heads.setCookie(user.getCookie());
			heads.setContentType("application/x-www-form-urlencoded");
			heads.setConnection("keep-alive");
			heads.setAccept("*/*");
			heads.setAcceptEncoding("gzip, deflate");
			heads.setAcceptLanguage("zh-CN,zh;q=0.9");
			heads.setxRequestedWith("ShockwaveFlash/29.0.0.171");
			Map<String,String> paramMap = new HashMap<String,String>();
			paramMap.put("id", xunwangVO.getLcid());
			paramMap.put("chapterid", xunwangVO.getChapterid());
			paramMap.put("lessonid", xunwangVO.getLessonid());
			paramMap.put("photoPath",xunwangVO.getFullpath());
			paramMap.put("t", Math.random()+"");
			
			response = instance.sendHttpPost(httpClient, heads, url, paramMap, null);
			
			int state = response.getStatusLine().getStatusCode();
			if(state == 200) {
				HttpEntity entity = response.getEntity();
				String html = EntityUtils.toString(entity,"UTF-8");
				if("1".equals(html.trim())) {
					//System.out.println(html);
				}else {
					log.error("logViewVideoPhoto失败",html);
				}
			}
		} catch (Exception e) {
			user.setFinished(true);
			log.error("上传人脸识别图片失败-->",e);
		}finally {
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	
	/**
	   *  完成一个视频后执行
	 */ 
	private void studyFinished(User user,XunwangVO xunwangVO) throws Exception{
		String url = xunwangVO.getBaseUrl() + "user/kjxx/studyFinished.do";
		CloseableHttpResponse response = null;
		CloseableHttpClient httpClient = null;
		try {
			HeadParmsVO heads = new HeadParmsVO();
			heads.setCookie(user.getCookie());
			heads.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
			heads.setConnection("keep-alive");
			heads.setAccept("application/json, text/javascript, */*; q=0.01");
			heads.setAcceptEncoding("gzip, deflate");
			heads.setAcceptLanguage("zh-CN,zh;q=0.9");
			heads.setxRequestedWith("XMLHttpRequest");
			Map<String,String> paramMap = new HashMap<String,String>();
			paramMap.put("cphId", xunwangVO.getCphId());
			paramMap.put("t", Math.random()+"");
			
			response = instance.sendHttpPost(httpClient, heads, url, paramMap, null);
			
			int state = response.getStatusLine().getStatusCode();
			if(state == 200) {
				HttpEntity entity = response.getEntity();
				String html = EntityUtils.toString(entity,"UTF-8");
				JSONObject json = JSONObject.fromObject(html);
				String code = json.getString("code");
				if("ok".equals(code.trim())) {
					log.info("studyFinished成功",html);
				}else {
					log.error("studyFinished失败",html);
				}
			}else {
			}
		} catch (Exception e) {
			user.setFinished(true);
			log.error("studyFinished失败-->",e);
		}finally {
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	
	//退出登录
	private void logout(User user,XunwangVO xunwangVO) throws Exception{
		CloseableHttpResponse response = null;
		CloseableHttpClient httpClient = null;
		String url = xunwangVO.getBaseUrl() + "common/logout.do";
		Map<String, String> maps = new HashMap<String, String>();
		try {
	        maps.put("t", Math.random()+"");//学员退出登录 
			String cookie = user.getCookie();
	        
			HeadParmsVO head = new HeadParmsVO();
	        head.setAccept("*/*");
	        head.setxRequestedWith("XMLHttpRequest");
			head.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
			head.setCookie(cookie);
			
			response = instance.sendHttpPost(httpClient, head, url, maps, null);
			int state = response.getStatusLine().getStatusCode();
			if(state == 200){
				HttpEntity entity = response.getEntity();  
				String html = EntityUtils.toString(entity,"UTF-8");
				JSONObject json = JSONObject.fromObject(html);
				if("y".equals(json.getString("code"))) {
				}else {
					log.error("退出登录失败--->",html);
				}
			}
		} catch (Exception e) {
			user.setFinished(true);
			log.error("退出登录异常--->",e);
		}finally {
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	
	//下载验证码图片，需要带cookie
	public String downloadImage(User user,XunwangVO xunwangVO) throws Exception{
		CloseableHttpResponse response = null;
		CloseableHttpClient httpClient = null;
		String name = DateFormatUtil.getDateStr(new Date(),"yyyyMMddHHmmss");
		HeadParmsVO head = new HeadParmsVO();
		head.setCookie(user.getCookie());
		String picName = getbaseImgaeUrl() + name + ".jpg";
		try {
			response = instance.sendHttpGet(httpClient,head,picUrl, null);
			int state = response.getStatusLine().getStatusCode();
			if(state == 200){
				HttpEntity entity = response.getEntity();
				byte[] data = EntityUtils.toByteArray(entity);
				//图片存入磁盘
				FileOutputStream fos = new FileOutputStream(picName);
				fos.write(data);
				fos.close();
				return picName;
			}
		} catch (Exception e) {
			user.setFinished(true);
			log.error("下载图片异常--->",e);
		}finally {
			HttpClientUtil.getInstance().closeResource(response);
		}
		return null;
	}
	
	private static String getbaseImgaeUrl() {
		return System.getProperty("os.name").toLowerCase()
				.startsWith("win") ? "D:\\photos\\image\\" : "/home/listen/photos/image/";
	}
	
}
